var $searchBtn,
	$searchForm,
	$listPage,
	$list,
	$editItem,
	$editModal,
	$saveBtn,
	$photoFile,
	$idCardFrontFile,
	$idCardBackFile,
	$previousPage,
	$nextPage;

var photoFileXhr,
	idCardFrontFileXhr,
	idCardBackFileXhr;

var RESULT,
	PARAM;

var renderList = function() {
	var skip = parseInt($searchForm.find('input.skip').val(), 10);
	var limit = parseInt($searchForm.find('input.limit').val(), 10);
	var nowPage = Math.floor(skip / PAGE.limit) + 1;
	var countPage = Math.ceil(RESULT.count / PAGE.limit);

	if (nowPage <= 1) {
		$previousPage.addClass('disabled');
	} else {
		$previousPage.removeClass('disabled');
	}
	if (nowPage >= countPage) {
		$nextPage.addClass('disabled');
	} else {
		$nextPage.removeClass('disabled');
	}

	$listPage.text(nowPage + '/' + countPage);
	$list.empty();
	$.each(RESULT.list, function(i, waiter) {

		var $waiter = $('<tr>' +
			'	<td>' + waiter.phone + '</td>' +
			'	<td>' + waiter.name + '</td>' +
			'	<td>' + waiter.trades.join(',') + '</td>' +
	        '   <td>' +
	        '       <button class="btn btn-default btn-xs edit" type="button"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></button>' +
	        // '       <button class="btn btn-default btn-xs remove" type="button"><span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span></button>' +
	        '   </td>' +
			'</tr>')
			.appendTo($list);
			$waiter.find('button.edit').click(function() {
				var $this = $(this);
				$editModal.find('input.id').val(waiter._id);
				$editModal.find('input.name').val(waiter.name);
				$editModal.find('input.phone').val(waiter.phone);
				$editModal.find('input.password').val('');
				$editModal.find('input.sex').each(function(i, radio) {
					radio.checked = waiter.sex == radio.value;
				});
				$editModal.find('input.idNum').val(waiter.idNum);
				$editModal.find('input.bankId').val(waiter.bankId);
				$editModal.find('input.bankName').val(waiter.bankName);
				$editModal.find('input.bankPerson').val(waiter.bankPerson);
				$editModal.find('input.hometown').val(waiter.hometown);
				$editModal.find('input.ageLevel').val(waiter.ageLevel);
				$editModal.find('input.empiricLevel').val(waiter.empiricLevel);
				$editModal.find('input.eduLevel').val(waiter.eduLevel);
				$editModal.find('input.wageLevel').val(waiter.wageLevel);
				$editModal.find('input.photo').val(waiter.photo);
				$editModal.find('img.photo').attr('src', '/entity/file/' + waiter.photo).show();
				$editModal.find('input.idCardFront').val(waiter.idCardFront),
				$editModal.find('img.idCardFront').attr('src', '/entity/file/' + waiter.idCardFront).show();
				$editModal.find('input.idCardBack').val(waiter.idCardBack)
				$editModal.find('img.idCardBack').attr('src', '/entity/file/' + waiter.idCardBack).show();
	            $.each(waiter.trades, function(i, trade) {
	                $editModal.find('input.trades[value="' + trade + '"]').each(function(j, checkbox) {
	                    checkbox.checked = true;
	                });
	            });
				$editModal.modal('show');
			});

	        $waiter.find('button.remove').click(function() {
	            if (window.confirm('是否要删除服务员“' + waiter.name + '”？')) {
	                deleteWaiter(waiter._id, function(err) {
	                    if (err) {
	                        alert('删除失败。');
	                    }

	                    $searchBtn.click();
	                });
	            }
	        });
	});
};

var init = function() {
	$createBtn = $('button.create-btn');
	$searchBtn = $('.search-btn');
	$searchForm = $('.search-form');
	$listPage = $('.pager .page');
	$list = $('tbody.list');
	$editItem = $('.edit');
	$editModal = $('#edit_modal');
	$saveBtn = $('#save_btn');
	$photoFile = $('.photoFile');
	$idCardFrontFile = $('.idCardFrontFile');
	$idCardBackFile = $('.idCardBackFile');
	$previousPage = $('li.previous');
	$nextPage = $('li.next');

	photoFileXhr = new XMLHttpRequest();
	idCardFrontFileXhr = new XMLHttpRequest();
	idCardBackFileXhr = new XMLHttpRequest();


    // 编辑模态窗口
    $editModal.on('hidden.bs.modal', function(event) { // 窗口隐藏
        $editModal.find('input:text').val('');
        $editModal.find('input[type="hidden"]').val('');
        $editModal.find('img').attr('src', '');
        $editModal.find('input:checkbox, input:radio').each(function(i, input) {
			input.checked = false;
        });
		$editModal.find('.has-error').removeClass('has-error');
		$editModal.find('.alert').hide();
    });

	$createBtn.click(function() {
		$editModal.modal('show');
	});

	$saveBtn.click(function() {
		$editModal.find('.has-error').removeClass('has-error');
		var id = $editModal.find('.id').val();
		var waiter = {
			name : $editModal.find('.name').val(),
			phone : $editModal.find('.phone').val(),
			password : $editModal.find('.password').val(),
			sex : $editModal.find('input.sex:checked').val(),
			idNum : $editModal.find('.idNum').val(),
			bankId : $editModal.find('.bankId').val(),
			bankName : $editModal.find('.bankName').val(),
			bankPerson : $editModal.find('.bankPerson').val(),
			hometown : $editModal.find('.hometown').val(),
			ageLevel : $editModal.find('.ageLevel').val(),
			empiricLevel : $editModal.find('.empiricLevel').val(),
			eduLevel : $editModal.find('.eduLevel').val(),
			wageLevel : $editModal.find('.wageLevel').val(),
			photo : $editModal.find('input.photo').val(),
			idCardFront : $editModal.find('input.idCardFront').val(),
			idCardBack : $editModal.find('input.idCardBack').val(),
			trades : []
		};

		$editModal.find('.trades:checked').each(function(i, checkbox) {
			waiter.trades.push(checkbox.value);
		});

		if (id) { // 修改
			putWaiter(id, waiter, function(err, result) {
				if (err) {
					var $errMsg = $editModal.find('.alert').hide().empty();
					if (result) {
						if (result.errors) {
							$.each(result.errors, function(key, errObj) {
								var $formGroup = $editModal.find('.' + key).parents('.form-group').addClass('has-error');
								$formGroup.find('.alert').append(errObj.message).show();
							});
						} else if (result.code == 11000) {
							$editModal.find('.phone').addClass('has-error');
							$errMsg.append('电话已存在。');
						}
					}
					return;
				}
				$editModal.modal('hide');
				$searchBtn.click();
			});
		} else { // 新增
			postWaiter(waiter, function(err, result) {
				if (err) {
					var $errMsg = $editModal.find('.alert').hide().empty();
					if (result) {
						if (result.errors) {
							$.each(result.errors, function(key, errObj) {
								var $formGroup = $editModal.find('.' + key).parents('.form-group').addClass('has-error');
								$formGroup.find('.alert').append(errObj.message).show();
							});
						} else if (result.code == 11000) {
							$editModal.find('.phone').addClass('has-error');
							$errMsg.append('电话已存在。');
						}
					}
					return;
				}
				$editModal.modal('hide');
				$searchBtn.click();
			});
		}

	});

	// 上传个人照片文件
	photoFileXhr.upload.addEventListener("progress", function(event) {
		if (event.lengthComputable) {
			var percentComplete = Math.round(event.loaded * 100 / event.total);
			$('.progress.photo .progress-bar').css('width', percentComplete.toString() + '%');
		}
	}, false);
	photoFileXhr.addEventListener("load", function(event) {
		$('img.photo').attr('src', '/entity/file/' + photoFileXhr.response._id);
		$editModal.find('input.photo').val(photoFileXhr.response._id);
		$('.progress.photo .progress-bar').css('width', '100%');
		$('.progress.photo').hide();
	}, false);
	photoFileXhr.addEventListener("error", function(event) {
		$('.progress.photo .progress-bar').addClass('progress-bar-danger');
	}, false);
	photoFileXhr.addEventListener("abort", function(event) {
		$('.progress.photo .progress-bar').css('width', '0');
		$('.progress.photo').hide();
	}, false);
	photoFileXhr.responseType = 'json';
	$photoFile.change(function() {
		$photoFile.each(function(i, input) {
			$.each(input.files, function(j, file) {
				var form = new FormData();
				form.append('file', file);
				photoFileXhr.open("POST", "/entity/file");
				photoFileXhr.send(form);
				$('.progress.photo').show();
				$('.progress.photo .progress-bar').removeClass('progress-bar-danger');
			});
		});
	});

	// 上传身份证正面
	idCardFrontFileXhr.upload.addEventListener("progress", function(event) {
		if (event.lengthComputable) {
			var percentComplete = Math.round(event.loaded * 100 / event.total);
			$('.progress.idCardFront .progress-bar').css('width', percentComplete.toString() + '%');
		}
	}, false);
	idCardFrontFileXhr.addEventListener("load", function(event) {
		$('img.idCardFront').attr('src', '/entity/file/' + idCardFrontFileXhr.response._id);
		$editModal.find('input.idCardFront').val(idCardFrontFileXhr.response._id);
		$('.progress.idCardFront .progress-bar').css('width', '100%');
		$('.progress.idCardFront').hide();
	}, false);
	idCardFrontFileXhr.addEventListener("error", function(event) {
		$('.progress.idCardFront .progress-bar').addClass('progress-bar-danger');
	}, false);
	idCardFrontFileXhr.addEventListener("abort", function(event) {
		$('.progress.idCardFront .progress-bar').css('width', '0');
		$('.progress.idCardFront').hide();
	}, false);
	idCardFrontFileXhr.responseType = 'json';
	$idCardFrontFile.change(function() {
		$idCardFrontFile.each(function(i, input) {
			$.each(input.files, function(j, file) {
				var form = new FormData();
				form.append('file', file);
				idCardFrontFileXhr.open("POST", "/entity/file");
				idCardFrontFileXhr.send(form);
				$('.progress.idCardFront').show();
				$('.progress.idCardFront .progress-bar').removeClass('progress-bar-danger');
			});
		});
	});

	// 上传身份证背面
	idCardBackFileXhr.upload.addEventListener("progress", function(event) {
		if (event.lengthComputable) {
			var percentComplete = Math.round(event.loaded * 100 / event.total);
			$('.progress.idCardBack .progress-bar').css('width', percentComplete.toString() + '%');
		}
	}, false);
	idCardBackFileXhr.addEventListener("load", function(event) {
		$('img.idCardBack').attr('src', '/entity/file/' + idCardBackFileXhr.response._id);
		$editModal.find('input.idCardBack').val(idCardBackFileXhr.response._id);
		$('.progress.idCardBack .progress-bar').css('width', '100%');
		$('.progress.idCardBack').hide();
	}, false);
	idCardBackFileXhr.addEventListener("error", function(event) {
		$('.progress.idCardBack .progress-bar').addClass('progress-bar-danger');
	}, false);
	idCardBackFileXhr.addEventListener("abort", function(event) {
		$('.progress.idCardBack .progress-bar').css('width', '0');
		$('.progress.idCardBack').hide();
	}, false);
	idCardBackFileXhr.responseType = 'json';
	$idCardBackFile.change(function() {
		$idCardBackFile.each(function(i, input) {
			$.each(input.files, function(j, file) {
				var form = new FormData();
				form.append('file', file);
				idCardBackFileXhr.open("POST", "/entity/file");
				idCardBackFileXhr.send(form);
				$('.progress.idCardBack').show();
				$('.progress.idCardBack .progress-bar').removeClass('progress-bar-danger');
			});
		});
	});

	// 查询
	$searchBtn.click(function(event) {
		$searchForm.find('input.skip').val(PAGE.skip);
		$searchForm.find('input.limit').val(PAGE.limit);
		PARAM = $('form.search-form').serialize();
		getWaiters(PARAM, function(err, result) {
			RESULT = result;
			renderList();
		});
	}).click();

	$previousPage.click(function() {
		var skip = parseInt($searchForm.find('input.skip').val(), 10);
		var limit = parseInt($searchForm.find('input.limit').val(), 10);
		skip -= limit;
		$searchForm.find('input.skip').val(skip);
		$searchForm.find('input.limit').val(limit);
		PARAM = $('form.search-form').serialize();
		getWaiters(PARAM, function(err, result) {
			RESULT = result;
			renderList();
		});

	});
	$nextPage.find('.icon-next').click(function() {
		var skip = parseInt($searchForm.find('input.skip').val(), 10);
		var limit = parseInt($searchForm.find('input.limit').val(), 10);
		skip += limit;
		$searchForm.find('input.skip').val(skip);
		$searchForm.find('input.limit').val(limit);
		PARAM = $('form.search-form').serialize();
		getWaiters(PARAM, function(err, result) {
			RESULT = result;
			renderList();
		});
	});

	$editItem.find('.create-btn').click(function() {
		$editItem.find('.error').removeClass('error');
		var id = $editItem.find('.id').val();
		var waiter = {
			name : $editItem.find('.name').val(),
			phone : $editItem.find('.phone').val(),
			password : $editItem.find('.password').val(),
			sex : $editItem.find('input.sex:checked').val(),
			idNum : $editItem.find('.idNum').val(),
			trades : [],
			hometown : $editItem.find('.hometown').val(),
			ageLevel : $editItem.find('.ageLevel').val(),
			empiricLevel : $editItem.find('.empiricLevel').val(),
			eduLevel : $editItem.find('.eduLevel').val(),
			wageLevel : $editItem.find('.wageLevel').val(),
			photo : $editItem.find('input.photo').val(),
			idCardFront : $editItem.find('input.idCardFront').val(),
			idCardBack : $editItem.find('input.idCardBack').val()
		};

		$editItem.find('.trades:checked').each(function(i, checkbox) {
			waiter.trades.push(checkbox.value);
		});

		postWaiter(waiter, function(err, result) {
			if (err) {
				var $errMsg = $editItem.find('.error-msg').empty();
				if (result) {
					if (result.errors) {
						$.each(result.errors, function(key, errObj) {
							$editItem.find('.' + key).addClass('error');
							$errMsg.append(errObj.message + '<br />');
						});
					} else if (result.code == 11000) {
						$editItem.find('.phone').addClass('error');
						$errMsg.append('电话已存在。');
					}
				}
				return;
			}

			$searchBtn.click();
		});
	});

	$editItem.find('.save-btn').click(function() {
		$editItem.find('.error').removeClass('error');
		var id = $editItem.find('.id').val();
		var waiter = {
			name : $editItem.find('.name').val(),
			phone : $editItem.find('.phone').val(),
			password : $editItem.find('.password').val()
		};

		putWaiter(id, waiter, function(err, result) {
			if (err) {
				var $errMsg = $editItem.find('.error-msg').empty();
				if (result) {
					if (result.errors) {
						$.each(result.errors, function(key, errObj) {
							$editItem.find('.' + key).addClass('error');
							$errMsg.append(errObj.message + '<br />');
						});
					} else if (result.code == 11000) {
						$editItem.find('.phone').addClass('error');
						$errMsg.append('电话已存在。');
					}
				}
				return;
			}

			$searchBtn.click();
		});

	});

	$editItem.find('.cancel-btn').click(function() {
		$editItem.hide().prev().show();
	});

	$editItem.find('input:file').change(function() {
		var $this = $(this);
		var inputName = $this.attr('input');
		if ($.trim($this.val())) {
			$editItem.find('span.' + inputName + 'Info').show().text('正在上传……');
			$this.parent().submit();
		}
	});

	$('.hidden-frame').load(function() {
		var $this = $(this);
		var inputName = $this.attr('input');
		try {
			var fileInfo = JSON.parse(this.contentDocument.body.innerText);
			$editItem.find('input:hidden.' + inputName).val(fileInfo._id);
			$editItem.find('img.' + inputName).attr('src', '/restful/file/' + fileInfo._id).show();
			$editItem.find('span.' + inputName + 'Info').hide().empty();
		} catch (err) {
			$editItem.find('span.' + inputName + 'Info').show().text('文件上传失败');
			$editItem.find('input:hidden.' + inputName).val('');
			$editItem.find('img.' + inputName).hide();
		}
	});
}
$(init);
